<template>
  <div class="left-nav" ref="navContainer">
    <ul>
      <li v-for="component in components"><a href="#" @click.prevent="navigate(component.page)">{{component.title}}</a></li>
    </ul>
  </div>
</template>
<script setup>
import { defineEmits, ref, onMounted, onBeforeUnmount } from 'vue';

// 定义一个 emit 函数，用于向父组件发送事件
const emit = defineEmits(['navigate']);
const components = ref([
    {
      title: 'Home',
      page: 'Home'
    },
    {
      title: 'Amazon',
      page: 'Amazon'
    },
    {
      title: '外部链接',
      page: 'Link'
    },
    {
      title: '简约计算器',
      page: 'Calculator'
    },
    {
      title: '复利计算器',
      page: 'Compound'
    },
    {
      title: '身份证验证',
      page: 'Validator'
    },
    {
      title: '密码生成器',
      page: 'Password'
    },
    {
      title: 'MD5加密器',
      page: 'Md5'
    },
    {
      title: '二维码生成',
      page: 'Qrcode'
    },
    {
      title: '迷你记事本',
      page: 'Notebook'
    },
    {
      title: '待办清单',
      page: 'Todo'
    },
    {
      title: '时间戳转换',
      page: 'Converter'
    },
    {
      title: '正则表达式',
      page: 'Regex'
    },
    {
      title: 'Git命令',
      page: 'Git'
    },
    {
      title: 'Linux命令',
      page: 'Linux'
    }
]);

// 定义一个函数来处理导航点击事件
function navigate(page) {
    console.log(page);
    // 发送一个带有页面名称的事件到父组件
    emit("navigate", page);
}

const navContainer = ref(null);
let resizeObserver;

onMounted(() => {
    resizeObserver = new ResizeObserver(handleResize);
    resizeObserver.observe(navContainer.value);
});

onBeforeUnmount(() => {
    if (resizeObserver) {
        resizeObserver.disconnect();
    }
});

function handleResize(entries) {
    const container = entries[0].target;
    if (container.clientWidth < container.scrollWidth) {
        container.style.overflowX = 'auto';
    } else {
        container.style.overflowX = 'hidden';
    }
}
</script>
   <style scoped lang="scss">
   @use "../assets/left-nav.scss";
   </style>